package com.eqdd.yiqidian.ui.tongxunlu.tag;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.arlib.floatingsearchview.FloatingSearchView;
import com.arlib.floatingsearchview.suggestions.model.SearchSuggestion;
import com.eqdd.yiqidian.BiaoqianItemActivityCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.StickyHeader1Custom;
import com.eqdd.yiqidian.adapter.FloatingItemDecoration;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.Person;
import com.eqdd.yiqidian.bean.ThirdBean;
import com.eqdd.yiqidian.bean.rebuild.FriendListResultBean;
import com.eqdd.yiqidian.bean.rebuild.TagInfoResultBean;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.ui.base.TextSuggestion;
import com.eqdd.yiqidian.ui.mine.UserCardActivity;
import com.eqdd.yiqidian.utils.ImageUtil;
import com.eqdd.yiqidian.utils.ItemDecorationUtil;
import com.eqdd.yiqidian.utils.PinYinUtil;
import com.eqdd.yiqidian.adapter.PinItemDecoration;
import com.eqdd.yiqidian.utils.SearchUtil;
import com.eqdd.yiqidian.utils.SideBarUtil;
import com.eqdd.yiqidian.utils.SwipeUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.eqdd.yiqidian.widget.WaveSideBarView;
import com.jakewharton.rxbinding.view.RxView;
import com.jakewharton.rxbinding.widget.RxSearchView;
import com.jakewharton.rxbinding.widget.RxTextView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;
import rx.android.schedulers.AndroidSchedulers;

public class TagItemActivity extends BaseActivity {
    private BiaoqianItemActivityCustom dataBinding;
    private String title;
    private SlimAdapterEx<FriendListResultBean> slimAdapterEx;
    private String labelid;
    private FloatingItemDecoration floatDeco;
    private List<FriendListResultBean> originData = new ArrayList<>();

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_biaoqian_item);
        title = getIntent().getStringExtra("title");
        initTopTitleBar(View.VISIBLE, title);
        initTopRightText("编辑人员", v -> {
            Bundle bundle = new Bundle();
            bundle.putString(Config.LABLEID, labelid);
            bundle.putParcelableArrayList("list", (ArrayList<FriendListResultBean>) originData);
            startActivityForResult(EditTagActivity.class, bundle, Config.EDIT_TAG);
        });

    }

    private String getLableds() {
        StringBuilder stringBuilder = new StringBuilder();
        Flowable.fromIterable(slimAdapterEx.getData())
                .subscribe(bean -> stringBuilder.append(bean.getGuid()).append(";"));
        if (TextUtils.isEmpty(stringBuilder)) {
            return "";
        } else {
            return stringBuilder.toString();
        }
    }

    @Override
    public void initData() {
        labelid = getIntent().getStringExtra(Config.LABLEID);
        SwipeUtil.openSwipe(this, dataBinding.recyclerView, (menuBridge, pos) -> {
            OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.REMOVE_TAG_PERSON)
                    .params("owner", user.getGuid())
                    .params("labelid", slimAdapterEx.getDataItem(pos).getId())
                    .params("labelfriends", getLableds().replace("", slimAdapterEx.getDataItem(pos).getGuid() + ";"))
                    .execute(new DialogCallBack<HttpResult>(TagItemActivity.this) {
                        @Override
                        public void onSuccess(Response<HttpResult> response) {
                            HttpResult httpResult = response.body();
                            ToastUtil.showShort(httpResult.getMsg());
                            if (httpResult.getStatus() == 200) {
                                menuBridge.closeMenu();
                                slimAdapterEx.getData().remove(pos);
                                slimAdapterEx.notifyItemRemoved(pos);
                            }
                        }
                    });
        });
        dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        slimAdapterEx = SlimAdapterEx.create().register(R.layout.list_item_16, new SlimInjector<FriendListResultBean>() {
            @Override
            public void onInject(FriendListResultBean data, IViewInjector injector) {

                injector.text(R.id.tv_upper_content, data.getUpname())
                        .text(R.id.tv_down_content, data.getUname())
                        .imageCircle(R.id.iv_head, data.getIphoto());
            }
        }).attachTo(dataBinding.recyclerView).updateData(new ArrayList());
        dataBinding.recyclerView.setSwipeItemClickListener((view, pos) -> {
            Bundle bundle = new Bundle();
            bundle.putString(Config.GUID, slimAdapterEx.getDataItem(pos).getGuid());
            startActivity(UserCardActivity.class, bundle);
        });
        SearchUtil.query(dataBinding.floatingSearchView, query -> {
            ArrayList<FriendListResultBean> newData = new ArrayList<>();
            if (originData != null) {
                Flowable.fromIterable(originData)
                        .filter(bean -> bean.getUname().contains(query)
                                || bean.getUpname().contains(query)
                                || PinYinUtil.getPinyin(bean.getUpname()).contains(query.toString().toUpperCase()))
                        .subscribe(
                                newData::add,
                                System.out::println,
                                () -> updateView(newData));
            }
        });
    }

    @Override
    public void setView() {

        OkGo.<HttpResult<TagInfoResultBean>>post(HttpConfig.BASE_URL + HttpConfig.TAG_PERSON_LIST)
                .params("owner", user.getGuid())
                .params("labelid", labelid)
                .execute(new DialogCallBack<HttpResult<TagInfoResultBean>>(TagItemActivity.this) {
                    @Override
                    public void onSuccess(Response<HttpResult<TagInfoResultBean>> response) {
                        HttpResult<TagInfoResultBean> httpResult = response.body();
                        ToastUtil.showShort(httpResult.getMsg());
                        if (httpResult.getStatus() == 200) {
                            originData = httpResult.getItems().getFriends();
                            updateView(originData);
                        }
                    }
                });

    }

    private void updateView(List<FriendListResultBean> datas) {
        Collections.sort(datas);
        slimAdapterEx.updateData(datas);
        if (floatDeco == null) {
            floatDeco = ItemDecorationUtil.openFloatDeco(TagItemActivity.this, dataBinding.recyclerView, datas, "upname");
        } else {
            ItemDecorationUtil.updateData(floatDeco, datas, "upname");
        }
        SideBarUtil.updateData(dataBinding.waveSideBar, datas, "upname");
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Config.EDIT_TAG && resultCode == Config.SUCCESS) {
            setView();
        }
    }
}
